<template>
   <!-- 查找 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="formInline.UserName" placeholder="请输入姓名" clearable />
    </el-form-item>
    <el-form-item label="状态">
      <el-select
        v-model="formInline.Status"
        placeholder="请选择"
        clearable
      >
        <el-option label="待审核" value="待审核" />
        <el-option label="已审核" value="已审核" />
      </el-select>
    </el-form-item>
    <el-form-item label="创建时间">
      <el-date-picker
        v-model="formInline.STime"
        type="date"
        placeholder="年/月/日"
        clearable
        value-format="YYYY-MM-DD"
      />
      至
      <el-date-picker
        v-model="formInline.ETime"
        type="date"
        placeholder="年/月/日"
        clearable
        value-format="YYYY-MM-DD"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="seach">查询</el-button>
    </el-form-item>
  </el-form>
    <el-button type="success" @click="dialogVisible=true">添加+</el-button>
      <!--显示用户-->
     <el-table :data="tableData" style="width: 100%">
    <el-table-column type="index" label="序号" width="70" />
    <el-table-column prop="userName" label="姓名" width="90" />
    <el-table-column prop="departmentId" label="部门" width="100" >
        <template v-slot="a">
            <span v-if="a.row.departmentId==1">IT信息部</span>
            <span v-if="a.row.departmentId==2">人力资源部</span>
            <span v-if="a.row.departmentId==3">财务部</span>
            <span v-if="a.row.departmentId==4">销售部</span>
            <span v-if="a.row.departmentId==5">行政部</span>
        </template>
    </el-table-column>
    <el-table-column prop="typeName" label="请假类型" width="90" />
    <el-table-column prop="" label="请假时间" width="190" >
        <template v-slot="scope">
           <span>{{ moment(scope.row.startTime).format("YYYY-MM-DD") }}至{{moment(scope.row.endTime).format("YYYY-MM-DD") }}</span>
        </template>
    </el-table-column>
    <el-table-column prop="hour" label="总时长" width="70" />
    <el-table-column prop="reason" label="请假事由" width="120" />
     <el-table-column prop="reportTime" label="报到时间" width="180" >
      <template v-slot="scope">
           <span>{{ moment(scope.row.reportTime).format("YYYY-MM-DD HH:mm:ss") }}</span>
      </template>
     </el-table-column>
    <el-table-column prop="leader" label="部门领导" width="120" />
    <el-table-column prop="status" label="审核状态" width="120" />
    <el-table-column prop="createTime" label="创建时间" width="180" >
      <template v-slot="scope">
           <span>{{ moment(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}</span>
      </template>
    </el-table-column>
        <el-table-column prop="remark" label="原因" width="120" />
    <el-table-column fixed="right" label="操作" min-width="200">
      <template #default="scope">
        <el-button  type="danger" size="small" v-if="scope.row.status=='待审核'" @click="handleClick(scope.row.id)">
          删除
        </el-button>
        <el-button  type="warning" size="small" v-if="scope.row.status=='待审核'" @click="Update(scope.row)">修改</el-button>
        <el-button  type="primary" size="small" v-if="scope.row.status=='待审核'" @click="UpdateStatus(scope.row)">审核</el-button>
      </template>
    </el-table-column>
  </el-table>
    <!--分页-->
  <table>
    <tr>
      <td>
         <el-pagination
      v-model:current-page="Page.PageIndex"
      v-model:page-size="Page.PageSize"
      :page-sizes="[15, 30, 45, 60]"
      layout="slot"
      :total="Page.totalCount"
    >
    共{{ Page.totalPage }}页
  </el-pagination>
        
      </td>
      <td>
         <el-pagination
      v-model:current-page="Page.PageIndex"
      v-model:page-size="Page.PageSize"
      :page-sizes="[15, 30, 45, 60]"
      layout="total, sizes,slot, prev, pager" prev-text="上一页"
      :total="Page.totalCount"
    >
     <el-button @click="Page.PageIndex=1">首页</el-button>
  </el-pagination>
   
      </td>
      <td>
         <el-pagination
      v-model:current-page="Page.PageIndex"
      v-model:page-size="Page.PageSize"
      :page-sizes="[15, 30, 45, 60]"
      layout=" next,slot ,jumper" next-text="下一页"
      :total="Page.totalCount"
    >
    <el-button @click="Page.PageIndex=Page.totalPage">尾页</el-button>
  </el-pagination>
    
      </td>
     
    </tr>
  </table>
    <!--添加用户-->
    <el-dialog
    v-model="dialogVisible"
    title="请假申请"
    width="800"

  >
    <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="姓名：" prop="userName">
      <el-input v-model="ruleForm.userName" disabled/>
    </el-form-item>
       <el-form-item label="部门:" prop="departmentId">
      <el-select v-model="ruleForm.departmentId" placeholder="请选择" disabled>
            <el-option 
          v-for="(label, value) in {1:'IT信息部',2:'人力资源部',3:'财务部',4:'销售部',5:'行政部'}" 
          :key="value"
          :label="label" 
          :value="value" />
          </el-select>
    </el-form-item>
  
    <el-form-item label="请假时间" required>
       <div class="form-row">

      <div class="time-range">
        自 <input type="datetime-local" v-model="ruleForm.startTime" @change="calculateTotalTime"> 
        至 <input type="datetime-local" v-model="ruleForm.endTime" @change="calculateTotalTime">
      </div>
    </div>
    <br><div>共计{{ ruleForm.day }}</div><br>
    <div class="form-row">
      <label></label>
      <div class="return-time">
        报到时间：<input type="datetime-local" v-model="ruleForm.reportTime">
      </div>
    </div>
    </el-form-item>

     <el-form-item label="请假类型" prop="typeName">
      <el-radio-group v-model="ruleForm.typeName">
        <el-radio value="事件">事件</el-radio>
        <el-radio value="病假">病假</el-radio>
        <el-radio value="婚假">婚假</el-radio>
        <el-radio value="丧假">丧假</el-radio>
        <el-radio value="产假">产假</el-radio>
        <el-radio value="补休">补休</el-radio>
        <el-radio value="工伤">工伤</el-radio>
        <el-radio value="其它">其它</el-radio>
      </el-radio-group>
    </el-form-item>
    
    <el-form-item label="请假事由" prop="reason">
      <el-input v-model="ruleForm.reason" type="textarea" />
    </el-form-item>
    <el-form-item label="部门领导:" prop="leader">
      <el-input v-model="ruleForm.leader" disabled/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        提交
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">取消</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
<!-- 修改用户 -->
   <el-dialog
    v-model="UpdatedialogVisible"
    title="请假申请"
    width="800"

  >
    <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="姓名：" prop="userName">
      <el-input v-model="ruleForm.userName" />
    </el-form-item>
       <el-form-item label="部门:" prop="departmentId">
              <el-select v-model="ruleForm.departmentId" placeholder="请选择">
                <el-option label="IT信息部" :value="1" />
                <el-option label="人力资源部" :value="2" />
                <el-option label="财务部" :value="3" />
                <el-option label="销售部" :value="4" />
                <el-option label="行政部" :value="5" />
                </el-select>
            </el-form-item>
  
    <el-form-item label="请假时间" required>
       <div class="form-row">

      <div class="time-range">
        自 <input type="datetime-local" v-model="ruleForm.startTime" @change="calculateTotalTime"> 
        至 <input type="datetime-local" v-model="ruleForm.endTime" @change="calculateTotalTime">
      </div>
    </div>
    <br><div>共计{{ ruleForm.day }}</div><br>
    <div class="form-row">
      <label></label>
      <div class="return-time">
        报到时间：<input type="datetime-local" v-model="ruleForm.reportTime">
      </div>
    </div>
    </el-form-item>

     <el-form-item label="请假类型" prop="typeName">
      <el-radio-group v-model="ruleForm.typeName">
        <el-radio value="事件">事件</el-radio>
        <el-radio value="病假">病假</el-radio>
        <el-radio value="婚假">婚假</el-radio>
        <el-radio value="丧假">丧假</el-radio>
        <el-radio value="产假">产假</el-radio>
        <el-radio value="补休">补休</el-radio>
        <el-radio value="工伤">工伤</el-radio>
        <el-radio value="其它">其它</el-radio>
      </el-radio-group>
    </el-form-item>
    
    <el-form-item label="请假事由" prop="reason">
      <el-input v-model="ruleForm.reason" type="textarea" />
    </el-form-item>
    <el-form-item label="部门领导:" prop="leader">
      <el-input v-model="ruleForm.leader" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="UpdateData">
        修改
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">取消</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
  <!-- 审核弹窗 -->
  <el-dialog
    v-model="UndialogVisible"
    title="请假审核"
    width="800"

  >
    <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="姓名：" prop="userName">
      <el-input v-model="ruleForm.userName" disabled/>
    </el-form-item>
       <el-form-item label="部门:" prop="departmentId">
              <el-select v-model="ruleForm.departmentId" placeholder="请选择" disabled>
                <el-option label="IT信息部" :value="1" />
                <el-option label="人力资源部" :value="2" />
                <el-option label="财务部" :value="3" />
                <el-option label="销售部" :value="4" />
                <el-option label="行政部" :value="5" />
                </el-select>
            </el-form-item>
  
    <el-form-item label="请假时间" required >
       <div class="form-row">

      <div class="time-range">
        自 <input type="datetime-local" v-model="ruleForm.startTime" @change="calculateTotalTime" disabled> 
        至 <input type="datetime-local" v-model="ruleForm.endTime" @change="calculateTotalTime" disabled>
      </div>
    </div>
    <br><div>共计{{ ruleForm.day }}</div><br>
    <div class="form-row">
      <label></label>
      <div class="return-time">
        报到时间：<input type="datetime-local" v-model="ruleForm.reportTime" disabled>
      </div>
    </div>
    </el-form-item>

     <el-form-item label="请假类型" prop="typeName">
      <el-radio-group v-model="ruleForm.typeName" >
        <el-radio value="事件">事件</el-radio>
        <el-radio value="病假">病假</el-radio>
        <el-radio value="婚假">婚假</el-radio>
        <el-radio value="丧假">丧假</el-radio>
        <el-radio value="产假">产假</el-radio>
        <el-radio value="补休">补休</el-radio>
        <el-radio value="工伤">工伤</el-radio>
        <el-radio value="其它">其它</el-radio>
      </el-radio-group>
    </el-form-item>
    
    <el-form-item label="请假事由" prop="reason">
      <el-input v-model="ruleForm.reason" type="textarea" disabled />
    </el-form-item>
     <el-form-item label="审核">
      <el-radio-group v-model="ruleForm.status">
        <el-radio value="已审核">通过</el-radio>
        <el-radio value="驳回" @click="">不通过</el-radio>
      <el-input v-model="ruleForm.remark" v-if="ruleForm.status=='驳回'" style="width: 320px;"placeholder="必填"/>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="UpdateApplyStatus">
        保存
      </el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
 
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import http from '../lanjieqi/lan1'
import axios from '../lanjieqi/lan'
import moment, { months } from 'moment'

const dialogVisible = ref(false)
const UpdatedialogVisible = ref(false)
const UndialogVisible = ref(false)


const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  "userName": localStorage.getItem('userName'),
  "departmentId": localStorage.getItem('departmentId'),
  "typeName": "",
  "startTime": "2025-06-27T09:06:34.673Z",
  "endTime": "2025-06-27T09:06:34.673Z",
  "reason": "",
  "leader": localStorage.getItem('managerName'),
  "hour": 0,
  "reportTime": "2025-06-27T09:06:34.673Z",
  "day":"",
  "id":"",
  "status": "",
  "remark": ""
})

const rules = reactive<FormRules>({
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 15, message: '用户名为2-15个字段', trigger: 'blur' },
  ],
  departmentId: [
    {
      required: true,
      message: '请输入部门名称',
      trigger: 'change',
    },
  ],
  typeName: [
    {
 
      required: true,
      message: '请选择请假类型',
      trigger: 'change',
    },
  ],
  startTime: [
    {
      type: 'date',
      required: true,
      message: '请选择时间',
      trigger: 'change',
    },
  ],
  endTime: [
    {
      type: 'date',
      required: true,
      message: '请选择时间',
      trigger: 'change',
    },
  ],
 
  reason: [
    { required: true, message: '请输入请假事由', trigger: 'blur' },
    {  max: 140, message: '最多只能写140个字', trigger: 'blur' },
  ],
  leader: [
    {
      required: true,
      message: '请输入部门领导',
      trigger: 'change',
    },
  ],
 remark: [
    {
 
      required: true,
      message: '必填',
      trigger: 'change',
    },
  ],
 
})
//添加
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) 
    {
      
      http.post("api/Apply/AddApply",ruleForm).then(res=>
      {
          if(res.data.code==200)
          {
            ElMessage.success(res.data.message)
            seach()
            dialogVisible.value=false
            ruleForm.day=''
            ruleForm.reason=''
            ruleForm.departmentId=''
            ruleForm.id=''
            ruleForm.endTime=''
            ruleForm.startTime=''
            ruleForm.userName=''
            ruleForm.typeName=''
            ruleForm.reportTime=''
            ruleForm.leader=''
          }
          else
          {
            ElMessage.error(res.data.message)
          
          }
      })
    } 
    else 
    {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
//计算总时长
// const claculateTotalTime=()=>
// {
//     if(!ruleForm.startTime||!ruleForm.endTime)return;
//     const start:any=new Date(ruleForm.startTime);
//     const end:any=new Date(ruleForm.endTime);
   
//     // 校验结束时间不能小于开始时间
//   if (end.getTime() < start.getTime()) {
//     ElMessage.error("结束时间不能小于开始时间");
//     ruleForm.endTime='';
//     return;
//   }

//     //计算完整的小时数
//     const diffMs=end-start;
//     const diffHours=Math.floor(diffMs/(1000*60*60));

//     //计算完整的天数部分
//     const fullDays=Math.floor(diffHours/8);
//     const remainingHours=diffHours%8;
//     //更新ruleForm.totalTime
//     ruleForm.day=`${fullDays}天`;
//     ruleForm.hour=fullDays*8+remainingHours;
// }


const calculateTotalTime = () => {
  if (!ruleForm.startTime || !ruleForm.endTime) return;

  const start = new Date(ruleForm.startTime);
  const end = new Date(ruleForm.endTime);

  // 校验结束时间不能小于开始时间
  if (end.getTime() < start.getTime()) {
    ElMessage.error("结束时间不能小于开始时间");
    ruleForm.endTime = '';
    return;
  }

  // 定义工作时间段 (9:00-17:00)
  const workStartHour = 9;
  const workEndHour = 17;
  const dailyWorkHours = 8;

  let totalHours = 0;
  let current = new Date(start);

  // 遍历每一天
  while (current <= end) {
    const currentDay = new Date(current);
    currentDay.setHours(0, 0, 0, 0);

    // 当天的工作开始时间
    const dayStart = new Date(currentDay);
    dayStart.setHours(workStartHour);
    
    // 当天的工作结束时间
    const dayEnd = new Date(currentDay);
    dayEnd.setHours(workEndHour);

    // 计算当天的工作时间段
    let segmentStart:any = current > dayStart ? current : dayStart;
    let segmentEnd:any = end < dayEnd ? end : dayEnd;

   // 如果是同一天且在工作时间内
    if (segmentStart < segmentEnd) {
      const hours = Math.floor((segmentEnd - segmentStart) / (1000 * 60 * 60)); // 取整小时数
      totalHours += hours > 0 ? hours : 0; // 确保不为负数
    }

    // 移动到下一天
    current = new Date(currentDay);
    current.setDate(current.getDate() + 1);
    current.setHours(workStartHour, 0, 0, 0);
  }

  // 计算完整工作天数和剩余小时数
  const fullDays = Math.floor(totalHours / dailyWorkHours);
  const remainingHours = totalHours % dailyWorkHours;

  // 更新显示
  ruleForm.day = `${fullDays}天${remainingHours}时`;
  ruleForm.hour = fullDays*8+remainingHours; // 总小时数
};


//显示
const tableData =ref([])
const Page=reactive
({
  PageIndex:1,
  PageSize:15,
  totalCount:0,
  totalPage:0
})
const formInline = reactive({
  Status: '',
  UserName: '',
  STime: '',
  ETime:'',
})
const seach=()=>
{
    axios.get("api/Apply/GetApplyShow",{params:
      {
        LoginName:localStorage.getItem('userName'),
        PageIndex:Page.PageIndex,
        PageSize:Page.PageSize,
        Status:formInline.Status,
        UserName:formInline.UserName,
        STime:formInline.STime,
        ETime:formInline.ETime
      }}).then(res=>
    {
        tableData.value=res.data.pageDatas
        Page.totalCount=res.data.totalCount
        Page.totalPage=Math.ceil(res.data.totalCount/Page.PageSize)
    })
}
//生命周期
onMounted(()=>
{
    seach()
})
//监听
watch(Page,()=>
{
  seach()
})
//删除
const handleClick = (id:any) => 
{
  ElMessageBox.confirm(
    '确认要删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => 
    {
      http.delete("api/Apply/DeleteApply",{params:{id:id}}).then(res=>
      {
            if(res.data.code==200)
            {
                ElMessage.success(res.data.message)
                seach()
            }
            else
            {
                ElMessage.error(res.data.message)
            }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
}

//修改
const Update=(row:any)=>
{
  ruleForm.userName=row.userName
  ruleForm.departmentId=row.departmentId
  ruleForm.endTime=row.endTime
  ruleForm.day=row.day
  ruleForm.id=row.id
  ruleForm.hour=row.hour
  ruleForm.leader=row.leader
  ruleForm.startTime=row.startTime
  ruleForm.reason=row.reason
  ruleForm.reportTime=row.reportTime
  ruleForm.typeName=row.typeName
  ruleForm.userName=row.userName
  calculateTotalTime();
  UpdatedialogVisible.value=true
}

const UpdateData=()=>
{
  http.put("api/Apply/UpdateApply",ruleForm).then(res=>
  {
    if(res.data.code==200)
    {
      ElMessage.success(res.data.message)
      seach()
      UpdatedialogVisible.value=false
        ruleForm.day=''
            ruleForm.reason=''
            ruleForm.departmentId=''
            ruleForm.id=''
            ruleForm.endTime=''
            ruleForm.startTime=''
            ruleForm.userName=''
            ruleForm.typeName=''
            ruleForm.reportTime=''
            ruleForm.leader=''
    }
    else
    {
      ElMessage.error(res.data.message)
    
    }
  })
}


//审核
const UpdateStatus=(row:any)=>
{
ruleForm.userName=row.userName
  ruleForm.departmentId=row.departmentId
  ruleForm.endTime=row.endTime
  ruleForm.day=row.day
  ruleForm.id=row.id
  ruleForm.hour=row.hour
  ruleForm.leader=row.leader
  ruleForm.startTime=row.startTime
  ruleForm.reason=row.reason
  ruleForm.reportTime=row.reportTime
  ruleForm.typeName=row.typeName
  ruleForm.userName=row.userName
  calculateTotalTime();
  UndialogVisible.value=true
}
const UpdateApplyStatus=()=>
{
  http.put("api/Apply/UpdateApplyStatus",ruleForm).then(res=>
  {
    if(res.data.code==200)
    {
      ElMessage.success(res.data.message)
      UndialogVisible.value=false
      seach()
    }
    else
    {
      ElMessage.error(res.data.message)
    
    }
  })
}
</script>



<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>


